package taskfactory

import (
	"github.com/gogf/gf/v2/os/gcron"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/glog"
)

var TaskFactory = make(map[string]*taskEntity)

func DoStartAllTask(log *glog.Logger, taskNameList []string) {
	if taskNameList == nil {
		return
	}

	for _, taskName := range taskNameList {
		taskItem := TaskFactory[taskName]
		//g.Dump(taskMap)
		if taskItem == nil {
			continue
		}

		var cronEntry *gcron.Entry
		if taskItem.Once {
			cronEntry, _ = gcron.AddOnce(gctx.GetInitCtx(), taskItem.Pattern, taskItem.Job, taskItem.Name)
		} else {
			cronEntry, _ = gcron.Add(gctx.GetInitCtx(), taskItem.Pattern, taskItem.Job, taskItem.Name)
		}
		log.Info(gctx.GetInitCtx(), "新增Task: ", cronEntry.Name)
		gcron.Start(taskItem.Name)
	}
}

func RegistryTask(pattern string, taskName string, job gcron.JobFunc) {
	TaskFactory[taskName] = getTask(taskName, pattern, job)
}

func RegistryOnceTask(pattern string, taskName string, job gcron.JobFunc) {
	t := getTask(taskName, pattern, job)
	t.Once = true
	TaskFactory[taskName] = t
}

func getTask(taskName string, pattern string, job gcron.JobFunc) *taskEntity {
	t := new(taskEntity)
	t.Name = taskName
	t.Pattern = pattern
	t.Job = job
	return t
}

type taskEntity struct {
	Pattern string
	Name    string
	Once    bool
	Job     gcron.JobFunc
}
